package com.example.tool.widget.mpview;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;

import com.github.mikephil.charting.animation.ChartAnimator;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.interfaces.dataprovider.LineDataProvider;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineScatterCandleRadarDataSet;
import com.github.mikephil.charting.renderer.LineChartRenderer;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.lang.ref.WeakReference;

/**
 * Created by weimf
 *
 * @author:weimf
 * @package:com.coolper.testsample.mychart
 * @desciption:${TODO} 曲线图表采用渐变
 * @date:2018/8/13
 */

public class CountLineChartRender extends LineChartRenderer {

    private int colorNum = 3;
    private Path mHighlightLinePath = new Path();

    int[] colorArr4 = new int[]{Color.parseColor("#f11321"),Color.parseColor("#f58200"),
            Color.parseColor("#fcee00"),Color.parseColor("#20d776") };

    int[] colorArr3 = new int[]{Color.parseColor("#f11321"),Color.parseColor("#fcba00"),
            Color.parseColor("#74cd3d")};

    public CountLineChartRender(LineDataProvider chart, ChartAnimator animator, ViewPortHandler viewPortHandler, int colorNum) {
        super(chart, animator, viewPortHandler);
        this.colorNum = colorNum;
    }

    @Override
    protected void drawHighlightLines(Canvas c, float x, float y, ILineScatterCandleRadarDataSet set) {
        // set color and stroke-width
        mHighlightPaint.setColor(set.getHighLightColor());
        mHighlightPaint.setStrokeWidth(set.getHighlightLineWidth());

        // draw highlighted lines (if enabled)
        mHighlightPaint.setPathEffect(set.getDashPathEffectHighlight());

        // draw vertical highlight lines
        if (set.isVerticalHighlightIndicatorEnabled()) {

            // create vertical path
            mHighlightLinePath.reset();
            /*源码屏蔽*/
            //自定义高亮指示线，让其不贯穿整个表格，长度为y值得高度
//            mHighlightLinePath.moveTo(x, y);
            /*end*/
            /*修改点：自定义高亮指示线,长度设置为曲线的高度*/
            mHighlightLinePath.moveTo(x, mViewPortHandler.contentTop());
            mHighlightLinePath.lineTo(x, mViewPortHandler.contentBottom());

            c.drawPath(mHighlightLinePath, mHighlightPaint);
        }

        // draw horizontal highlight lines
        if (set.isHorizontalHighlightIndicatorEnabled()) {

            // create horizontal path
            mHighlightLinePath.reset();
            mHighlightLinePath.moveTo(mViewPortHandler.contentLeft(), y);
            mHighlightLinePath.lineTo(mViewPortHandler.contentRight(), y);

            c.drawPath(mHighlightLinePath, mHighlightPaint);
        }
    }

    /**
     * 重写 绘制数据集
     * @param c
     */
    @Override
    public void drawData(Canvas c) {

        int width = (int) mViewPortHandler.getChartWidth();
        int height = (int) mViewPortHandler.getChartHeight();

        Bitmap drawBitmap = mDrawBitmap == null ? null : mDrawBitmap.get();

        if (drawBitmap == null
                || (drawBitmap.getWidth() != width)
                || (drawBitmap.getHeight() != height)) {

            if (width > 0 && height > 0) {
                drawBitmap = Bitmap.createBitmap(width, height, mBitmapConfig);
                mDrawBitmap = new WeakReference<>(drawBitmap);
                mBitmapCanvas = new Canvas(drawBitmap);
            } else
                return;
        }

        drawBitmap.eraseColor(Color.TRANSPARENT);
        /*以下：添加的渐变色源码（根据曲线绘制区域，从上而下颜色渐变）*/
//        float y0 = colorNum == 3?mViewPortHandler.contentTop()+200:mViewPortHandler.contentTop()+100;
//        float y1 = colorNum == 3?mViewPortHandler.contentBottom()-200:mViewPortHandler.contentBottom()-100;
//        paintSetShader(mRenderPaint, colorNum == 3 ?colorArr3:colorArr4, mViewPortHandler.contentLeft(), y0,
//                mViewPortHandler.contentLeft(), y1);
//        mRenderPaint.setStyle(Paint.Style.STROKE);
        /*end*/
        LineData lineData = mChart.getLineData();

        for (ILineDataSet set : lineData.getDataSets()) {

            if (set.isVisible())
                drawDataSet(c, set);
        }

        c.drawBitmap(drawBitmap, 0, 0, mRenderPaint);
    }

    /**
     * 重写，绘制贝塞尔曲线
     * @param dataSet
     */
    @Override
    protected void drawCubicBezier(ILineDataSet dataSet) {
        float phaseX = Math.max(0.f, Math.min(1.f, mAnimator.getPhaseX()));
        float phaseY = mAnimator.getPhaseY();

        Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());
        mXBounds.set(mChart, dataSet);

        float intensity = dataSet.getCubicIntensity();
        cubicPath.reset();

        float prevDx = 0f;
        float prevDy = 0f;
        float curDx = 0f;
        float curDy = 0f;
        if (mXBounds.range >= 1) {

            final int firstIndex = mXBounds.min + 1;
            final int lastIndex = mXBounds.min + mXBounds.range;

            Entry prevPrev;
            Entry prev = dataSet.getEntryForIndex(Math.max(firstIndex - 2, 0));
            Entry cur = dataSet.getEntryForIndex(Math.max(firstIndex - 1, 0));
            Entry next = cur;
            int nextIndex = -1;

            if (cur == null) return;

            // let the spline start
            cubicPath.moveTo(cur.getX(), cur.getY() * phaseY);

            for (int j = mXBounds.min + 1; j <= mXBounds.range + mXBounds.min; j++) {

                prevPrev = prev;
                prev = cur;
                cur = nextIndex == j ? next : dataSet.getEntryForIndex(j);

                nextIndex = j + 1 < dataSet.getEntryCount() ? j + 1 : j;
                next = dataSet.getEntryForIndex(nextIndex);

                prevDx = (cur.getX() - prevPrev.getX()) * intensity;
                prevDy = (cur.getY() - prevPrev.getY()) * intensity;
                curDx = (next.getX() - prev.getX()) * intensity;
                curDy = (next.getY() - prev.getY()) * intensity;

                cubicPath.cubicTo(prev.getX() + prevDx, (prev.getY() + prevDy) * phaseY,
                        cur.getX() - curDx,
                        (cur.getY() - curDy) * phaseY,
                        cur.getX(), cur.getY() * phaseY);
            }
        }

        // if filled is enabled, close the path
        if (dataSet.isDrawFilledEnabled()) {

            cubicFillPath.reset();
            cubicFillPath.addPath(cubicPath);

            drawCubicFill(mBitmapCanvas, dataSet, cubicFillPath, trans, mXBounds);
        }
        /*与源码不同点：自己屏蔽的源码，（颜色采用渐变的颜色）*/
//        mRenderPaint.setColor(dataSet.getColor());
//        mRenderPaint.setStyle(Paint.Style.STROKE);
        /*end*/
        trans.pathValueToPixel(cubicPath);

        mBitmapCanvas.drawPath(cubicPath, mRenderPaint);
        mRenderPaint.setPathEffect(null);
        mBitmapCanvas.save();
    }

    /**
     * 为画笔 设置 渐变渲染器
     * @param paint
     * @param shaders
     * @param x0  图表区域
     * @param y0
     * @param x1
     * @param y1
     */
    protected void paintSetShader(Paint paint, int[] shaders, float x0, float y0, float x1, float y1){
        if(shaders != null && shaders.length>1) {
            float[] position = new float[shaders.length];
            float v = 1f/shaders.length;
            float temp = 0;
            if(shaders.length>2) {
                for(int i = 0; i<shaders.length; i++) {
                    position[i] = temp;
                    temp += v;
                }
            }else {
                position[0] = 0;
                position[1] = 1;
            }
            paint.setShader(new LinearGradient(x0, y0, x1, y1, shaders, position, Shader.TileMode.CLAMP));
        }else if(paint.getShader() != null) {
            paint.setShader(null);
        }
    }

}